import { Config } from "./Config";
import { Cube } from "./Cube";
import { Tooler } from "./tooler";

export class Col {
  indexCol: number = 0;
  cubes: Cube[] = [];

  constructor(indexCol: number) {
    this.indexCol = indexCol;
  }

  init(): void {
    for (let i = 0; i < Config.CARDS_PER_COL; i++) {
      const cube = new Cube(this.indexCol);
      cube.setType(Tooler.getRandomInt(0, 10));
      this.cubes.push(cube);
    }
  }

  add(items: { idxNo: number; type: number }[]): Cube[] {
    const list: Cube[] = items.map(item => {
      const cube = new Cube(item.idxNo);
      cube.setType(item.type);
      return cube;
    });
    this.cubes = list.concat(this.cubes);
    return list;
  }

  initPosition(total: number, idx: number): void {
    this.cubes.forEach((cube, i) => {
      cube.moveDistance = -total * Config.CARD_HEIGHT;
      cube.moveTimer = Config.SCROLL_TIMER + (0.5 - idx % 2) * 2 * Config.GAP_TIMER * idx;
    });
  }

  fixPosition(connList: { indexCol: number; py: number }[]): void {
    this.cubes.forEach(cube => {
      let distance = 0;
      connList.forEach(i => {
        if (cube.indexCol === i.indexCol && cube.py > i.py) {
          distance -= Config.CARD_HEIGHT;
        }
      });
      cube.moveDistance = distance;
      cube.moveTimer = Config.DROP_DOWN_TIMER;
    });
  }

  updateOrder(): void {
    this.cubes.forEach(cube => cube.updateOrder());
  }

  removeOutside() {
    this.cubes = this.cubes.filter(cube => {
      if (cube.isOutside) {
        cube.remove()
      }
      return !cube.isOutside
    });
  }

  removeBottom() {
    this.cubes = this.cubes.filter(cube => {
      if (cube.isBottom) {
        cube.remove()
      }
      return !cube.isBottom
    });
  }

  removeConn(connList:any[]) {
    this.cubes = this.cubes.filter(cube => {
      const has = connList.includes(cube)
      if (has) {
        cube.remove()
      }
      return !has
    });
  }

  play(): void {
    this.cubes.forEach(cube => cube.play());
  }
}